from PyQt6.QtCore import QThread, pyqtSignal
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, WebDriverException, StaleElementReferenceException
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver.safari.service import Service as SafariService
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from selenium.webdriver.common.keys import Keys

import os
import time
import sys
import platform
import re
from typing import List, Dict, Optional

# 导入自定义模块
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from utils.file_utils import read_prompt_file, generate_follow_up_prompt, generate_note
from .unicode_handler import clean_unicode_text  # 导入新的Unicode处理函数

class BrowserWorker(QThread):
    """执行浏览器自动化的工作线程"""
    
    # 定义信号
    progress_update = pyqtSignal(int, str)  # 进度更新信号 (进度值, 状态消息)
    status_update = pyqtSignal(str, str)    # 状态更新信号 (状态类型, 状态值)
    finished = pyqtSignal(str)              # 完成信号 (笔记内容)
    error = pyqtSignal(str)                 # 错误信号 (错误消息)
    
    # 定义状态常量
    STATUS_IDLE = "idle"
    STATUS_CONNECTING = "connecting"
    STATUS_CONNECTED = "connected"
    STATUS_SELECTING_MODEL = "selecting_model"
    STATUS_MODEL_SELECTED = "model_selected"
    STATUS_CONVERSING = "conversing"
    STATUS_GENERATING_NOTE = "generating_note"
    STATUS_COMPLETED = "completed"
    STATUS_ERROR = "error"
    
    def __init__(self, prompt_file: str, iterations: int, browser_type: str = "chrome", 
                 follow_up_prompts: Optional[List[str]] = None, parent=None):
        """
        初始化浏览器工作线程
        
        Args:
            prompt_file: 提示词文件路径
            iterations: 对话轮次
            browser_type: 浏览器类型 ("chrome", "firefox", "edge", "safari")
            follow_up_prompts: 多轮对话提示词列表
            parent: 父对象
        """
        super().__init__(parent)
        
        self.prompt_file = prompt_file
        self.iterations = iterations
        self.browser_type = browser_type.lower()
        self.follow_up_prompts = follow_up_prompts
        
        self._is_running = False
        self.driver = None
        self.current_status = self.STATUS_IDLE
    
    def run(self):
        """线程主执行函数"""
        self._is_running = True
        conversations = []
        
        try:
            # 设置初始状态
            self._update_status(self.STATUS_IDLE, "准备启动自动化流程")
            
            # 浏览器自动化阶段
            self._update_progress(5, "正在初始化浏览器...")
            self.driver = self._initialize_browser()
            
            # 访问Claude网站
            self._update_status(self.STATUS_CONNECTING, "正在连接")
            self._update_progress(15, "正在访问Claude网站...")
            self._access_claude_website()
            
            # 登录网站
            self._update_progress(20, "正在登录Claude网站...")
            self._login_to_claude()
            
            # 选择Claude模型
            self._update_status(self.STATUS_SELECTING_MODEL, "正在选择")
            self._update_progress(25, "正在选择Claude模型...")
            self._select_claude_model()
            self._update_status(self.STATUS_MODEL_SELECTED, "已选择")
            
            # 笔记生成阶段
            self._update_progress(40, "正在读取提示词文件...")
            prompt = read_prompt_file(self.prompt_file)
            
            # 执行对话
            self._update_status(self.STATUS_CONVERSING, "进行对话中")
            self._update_progress(50, "正在进行第1轮对话...")
            conversations = self._conduct_conversations(prompt)
            
            # 生成笔记
            self._update_status(self.STATUS_GENERATING_NOTE, "生成笔记中")
            self._update_progress(90, "正在生成笔记...")
            note_content = generate_note(conversations, self.prompt_file)
            
            # 发送完成信号
            self._update_status(self.STATUS_COMPLETED, "完成")
            self._update_progress(100, "自动化流程完成")
            self.finished.emit(note_content)
            
        except Exception as e:
            self._update_status(self.STATUS_ERROR, "错误")
            self.error.emit(f"自动化过程错误: {str(e)}")
        finally:
            # 关闭浏览器
            self._cleanup()
            self._is_running = False
    
    def stop(self):
        """停止线程执行"""
        if self._is_running:
            self._update_progress(0, "正在停止自动化流程...")
            self._is_running = False
            self._cleanup()
    
    def _cleanup(self):
        """清理资源"""
        if self.driver:
            try:
                self.driver.quit()
            except:
                pass
            self.driver = None
    
    def _update_progress(self, value: int, message: str) -> None:
        """
        更新进度信息
        
        Args:
            value: 进度值 (0-100)
            message: 状态消息
        """
        if self._is_running:
            self.progress_update.emit(value, message)
    
    def _update_status(self, status: str, message: str) -> None:
        """
        更新状态信息
        
        Args:
            status: 状态类型
            message: 状态描述
        """
        self.current_status = status
        
        if status == self.STATUS_CONNECTING or status == self.STATUS_CONNECTED:
            self.status_update.emit("site", message)
        elif status.startswith("model") or status == self.STATUS_SELECTING_MODEL:
            self.status_update.emit("model", message)
    
    def _initialize_browser(self) -> webdriver.Remote:
        """
        初始化浏览器
        
        Returns:
            WebDriver实例
        
        Raises:
            Exception: 如果浏览器初始化失败
        """
        try:
            if self.browser_type == "chrome":
                self._update_progress(8, "初始化Chrome浏览器...")
                options = webdriver.ChromeOptions()
                options.add_argument("--start-maximized")
                options.add_argument("--disable-extensions")
                options.add_argument("--disable-notifications")
                # options.add_argument("--headless")  # 无头模式，通常不建议对于自动化交互
                
                # 更新为Selenium 4.x兼容的初始化方式
                service = ChromeService(executable_path=ChromeDriverManager().install())
                driver = webdriver.Chrome(service=service, options=options)
                
            elif self.browser_type == "firefox":
                self._update_progress(8, "初始化Firefox浏览器...")
                options = webdriver.FirefoxOptions()
                options.add_argument("--start-maximized")
                options.add_argument("--disable-extensions")
                options.add_argument("--disable-notifications")
                
                # 更新为Selenium 4.x兼容的初始化方式
                service = FirefoxService(executable_path=GeckoDriverManager().install())
                driver = webdriver.Firefox(service=service, options=options)
                
            elif self.browser_type == "edge":
                self._update_progress(8, "初始化Edge浏览器...")
                options = webdriver.EdgeOptions()
                options.add_argument("--start-maximized")
                options.add_argument("--disable-extensions")
                options.add_argument("--disable-notifications")
                
                # 更新为Selenium 4.x兼容的初始化方式
                service = EdgeService(executable_path=EdgeChromiumDriverManager().install())
                driver = webdriver.Edge(service=service, options=options)
                
            elif self.browser_type == "safari":
                self._update_progress(8, "初始化Safari浏览器...")
                # Safari需要提前在系统中启用WebDriver
                # 在macOS终端执行: safaridriver --enable
                if platform.system() != 'Darwin':
                    raise Exception("Safari浏览器自动化仅支持macOS系统")
                
                # 使用默认服务
                service = SafariService()
                driver = webdriver.Safari(service=service)
                
            else:
                raise Exception(f"不支持的浏览器类型: {self.browser_type}")
                
            # 设置隐式等待时间
            driver.implicitly_wait(10)
            self._update_progress(12, f"{self.browser_type.capitalize()}浏览器初始化完成")
            return driver
            
        except Exception as e:
            raise Exception(f"浏览器初始化失败: {str(e)}")
    
    def _access_claude_website(self) -> None:
        """
        访问Claude网站
        
        Raises:
            Exception: 如果访问网站失败
        """
        # 添加重试机制
        max_retries = 3
        retry_delay = 5
        
        # Claude网站可能的URLs列表
        claude_urls = [
            "https://china.aikeji.vip/",
            "https://claudeai.ai/",
            "https://claude.ai/"
        ]
        
        # 尝试每个URL和重试
        for url_index, base_url in enumerate(claude_urls):
            # 重置重试次数
            current_retries = 0
            
            while current_retries < max_retries:
                try:
                    # 访问网站前清除缓存和cookies
                    if current_retries > 0 or url_index > 0:
                        self._update_progress(18, f"重试前清除浏览器缓存和Cookies (URL {url_index+1}/{len(claude_urls)}, 尝试 {current_retries+1}/{max_retries})...")
                        self.driver.delete_all_cookies()
                        try:
                            # 清除缓存 (仅适用于Chrome)
                            if self.browser_type == "chrome":
                                self.driver.execute_cdp_cmd('Network.clearBrowserCache', {})
                        except:
                            pass
                    
                    # 尝试访问网站
                    self._update_progress(19, f"正在打开Claude网站 {base_url} (URL {url_index+1}/{len(claude_urls)}, 尝试 {current_retries+1}/{max_retries})...")
                    
                    # 设置页面加载超时时间
                    self.driver.set_page_load_timeout(45)  # 增加超时时间
                    
                    # 访问网站
                    self.driver.get(base_url)
                    
                    # 等待页面加载
                    self._update_progress(20, "等待页面加载...")
                    WebDriverWait(self.driver, 30).until(
                        EC.presence_of_element_located((By.TAG_NAME, "body"))
                    )
                    
                    # 更新状态
                    self._update_status(self.STATUS_CONNECTED, "已连接")
                    self._update_progress(23, f"Claude网站 {base_url} 已连接")
                    return
                    
                except TimeoutException:
                    error_msg = f"访问Claude网站 {base_url} 超时，第{current_retries+1}次尝试"
                    
                    if current_retries < max_retries - 1:
                        self._update_progress(20, f"{error_msg}，将在{retry_delay}秒后重试...")
                        time.sleep(retry_delay)
                        retry_delay *= 1.5  # 指数退避但增长速度缓和
                        current_retries += 1
                        continue
                    else:
                        # 最后一次尝试此URL，尝试截图
                        try:
                            screenshot_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 
                                                       f"connection_timeout_url{url_index+1}.png")
                            self.driver.save_screenshot(screenshot_path)
                            self._update_progress(20, f"已保存超时截图到 {screenshot_path}")
                        except:
                            pass
                        
                        # 尝试下一个URL
                        break
                        
                except WebDriverException as e:
                    error_msg = f"访问Claude网站 {base_url} 错误: {str(e)}"
                    
                    # 检查是否是网络连接问题
                    connection_errors = ["ERR_CONNECTION", "ERR_NAME_NOT_RESOLVED", "ERR_INTERNET_DISCONNECTED", 
                                        "ERR_PROXY_CONNECTION", "ERR_NETWORK_CHANGED", "ERR_CONNECTION_TIMED_OUT"]
                    
                    is_connection_error = any(err in str(e) for err in connection_errors)
                    
                    if is_connection_error and current_retries < max_retries - 1:
                        self._update_progress(20, f"{error_msg}，将在{retry_delay}秒后重试...")
                        time.sleep(retry_delay)
                        retry_delay *= 1.5  # 指数退避但增长速度缓和
                        current_retries += 1
                        continue
                        
                    # 最后一次尝试此URL，尝试截图
                    try:
                        screenshot_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 
                                                   f"connection_error_url{url_index+1}.png")
                        self.driver.save_screenshot(screenshot_path)
                        self._update_progress(20, f"已保存错误截图到 {screenshot_path}")
                    except:
                        pass
                    
                    # 尝试下一个URL
                    break
        
        # 所有URL都尝试失败
        raise Exception("所有Claude网站URL都无法连接，请检查网络连接或尝试稍后重试。建议：\n" +
                      "1. 检查您的网络连接是否稳定\n" +
                      "2. 确认您能够在浏览器中手动访问Claude网站\n" +
                      "3. 如果使用代理，请检查代理设置\n" +
                      "4. 可能需要VPN才能访问某些Claude站点")
    
    def _login_to_claude(self) -> None:
        """
        登录Claude网站
        
        Raises:
            Exception: 如果登录失败
        """
        try:
            # 等待登录按钮出现
            self._update_progress(21, "查找登录按钮...")
            
            # 尝试多种选择器找到登录按钮
            login_button_selectors = [
                "//button[contains(.//span, '点击登录')]",
                "//button[contains(@class, 'n-button') and .//span[contains(text(), '点击登录')]]",
                "//button[@tabindex='0' and .//span[contains(text(), '点击登录')]]",
                "//span[contains(text(), '点击登录')]/parent::button"
            ]
            
            login_button = None
            for selector in login_button_selectors:
                try:
                    self._update_progress(22, f"尝试使用选择器 {selector} 查找登录按钮...")
                    login_button = WebDriverWait(self.driver, 10).until(
                        EC.element_to_be_clickable((By.XPATH, selector))
                    )
                    if login_button:
                        break
                except:
                    continue
            
            if not login_button:
                # 检查是否已经登录
                try:
                    # 检查是否已经显示模型选择页面
                    if self.driver.find_elements(By.XPATH, "//div[contains(@class, 'n-card__content')]") or \
                       self.driver.find_elements(By.XPATH, "//div[contains(@class, 'boxclass')]"):
                        self._update_progress(23, "检测到已登录状态，跳过登录步骤")
                        return
                except:
                    pass
                
                # 登录按钮未找到，尝试截图记录
                try:
                    screenshot_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 
                                               "login_screen.png")
                    self.driver.save_screenshot(screenshot_path)
                    self._update_progress(22, f"找不到登录按钮，已保存截图到 {screenshot_path}")
                except:
                    pass
                
                # 尝试记录当前页面源码
                try:
                    page_source_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 
                                               "login_page_source.html")
                    with open(page_source_path, 'w', encoding='utf-8') as f:
                        f.write(self.driver.page_source)
                    self._update_progress(22, f"已保存页面源码到 {page_source_path}")
                except:
                    pass
                
                raise Exception("找不到登录按钮，可能网站结构已更改")
            
            # 点击登录按钮
            self._update_progress(22, "点击登录按钮...")
            
            # 使用JavaScript点击，这通常更可靠
            self.driver.execute_script("arguments[0].scrollIntoView(true);", login_button)
            time.sleep(0.5)  # 等待滚动完成
            self.driver.execute_script("arguments[0].click();", login_button)
            
            # 等待登录表单加载
            self._update_progress(23, "等待登录表单加载...")
            time.sleep(2)  # 给予足够的时间加载登录表单
            
            # 输入账号和密码
            try:
                # 查找账号输入框
                email_selectors = [
                    "//input[@id='email']",
                    "//input[@name='email']",
                    "//input[@inputmode='email']",
                    "//input[contains(@class, 'input') and @type='text']"
                ]
                
                email_input = None
                for selector in email_selectors:
                    try:
                        self._update_progress(24, f"尝试查找账号输入框 {selector}...")
                        email_input = WebDriverWait(self.driver, 5).until(
                            EC.presence_of_element_located((By.XPATH, selector))
                        )
                        if email_input:
                            break
                    except:
                        continue
                
                if not email_input:
                    raise Exception("找不到账号输入框")
                
                # 输入账号
                self._update_progress(25, "输入账号...")
                email_input.clear()
                email_input.send_keys("linwenhui")
                time.sleep(0.5)  # 短暂等待
                
                # 查找密码输入框
                password_selectors = [
                    "//input[@id='password']",
                    "//input[@name='password']",
                    "//input[@type='password']",
                    "//input[contains(@class, 'input') and @type='password']"
                ]
                
                password_input = None
                for selector in password_selectors:
                    try:
                        self._update_progress(26, f"尝试查找密码输入框 {selector}...")
                        password_input = WebDriverWait(self.driver, 5).until(
                            EC.presence_of_element_located((By.XPATH, selector))
                        )
                        if password_input:
                            break
                    except:
                        continue
                
                if not password_input:
                    raise Exception("找不到密码输入框")
                
                # 输入密码
                self._update_progress(27, "输入密码...")
                password_input.clear()
                password_input.send_keys("lwh123456")
                time.sleep(0.5)  # 短暂等待
                
                # 查找登录表单的提交按钮
                submit_selectors = [
                    "//button[@type='submit']",
                    "//button[contains(text(), '登录')]",
                    "//button[contains(.//span, '登录')]",
                    "//button[contains(@class, 'submit')]",
                    "//button[contains(@class, 'login')]"
                ]
                
                submit_button = None
                for selector in submit_selectors:
                    try:
                        self._update_progress(28, f"尝试查找提交按钮 {selector}...")
                        submit_button = WebDriverWait(self.driver, 5).until(
                            EC.element_to_be_clickable((By.XPATH, selector))
                        )
                        if submit_button:
                            break
                    except:
                        continue
                
                if not submit_button:
                    # 如果找不到提交按钮，尝试按回车键提交表单
                    self._update_progress(28, "找不到提交按钮，尝试按回车键提交...")
                    password_input.send_keys(Keys.RETURN)
                else:
                    # 点击提交按钮
                    self._update_progress(28, "点击提交按钮...")
                    self.driver.execute_script("arguments[0].click();", submit_button)
                
            except Exception as e:
                # 记录错误并截图
                try:
                    screenshot_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 
                                               "login_form_error.png")
                    self.driver.save_screenshot(screenshot_path)
                    self._update_progress(29, f"登录表单填写出错: {str(e)}，已保存截图到 {screenshot_path}")
                except:
                    pass
                
                raise Exception(f"登录表单填写出错: {str(e)}")
            
            # 等待登录过程完成
            self._update_progress(29, "等待登录处理...")
            time.sleep(5)  # 给予足够的时间完成登录过程
            
            # 检查是否成功登录
            try:
                # 等待模型选择页面出现
                WebDriverWait(self.driver, 20).until(
                    EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'n-card__content')]"))
                )
                self._update_progress(30, "登录成功")
            except:
                # 如果未检测到模型选择页面，可能登录失败
                try:
                    screenshot_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 
                                                "login_failed.png")
                    self.driver.save_screenshot(screenshot_path)
                    self._update_progress(30, f"登录可能失败，已保存截图到 {screenshot_path}")
                except:
                    pass
                
                raise Exception("登录过程可能未成功完成，未检测到模型选择页面")
                
        except TimeoutException:
            raise Exception("登录过程超时，请检查网络连接或网站结构")
        except WebDriverException as e:
            raise Exception(f"登录过程中浏览器错误: {str(e)}")
        except Exception as e:
            raise Exception(f"登录过程中发生错误: {str(e)}")
    
    def _select_claude_model(self) -> None:
        """
        选择Claude模型
        
        Raises:
            Exception: 如果无法选择模型
        """
        try:
            # 先等待页面完全加载
            self._update_progress(28, "等待模型选择界面加载...")
            time.sleep(3)  # 额外等待时间，确保页面完全加载
            
            # 尝试多种选择器定位Claude模型
            self._update_progress(29, "尝试不同方式查找Claude模型...")
            
            # 检查是否已经在对话界面
            try:
                # 检查是否有输入框存在
                input_selectors = [
                    # 最新的输入框定位
                    "//div[contains(@class, 'ProseMirror')]",
                    "//div[@contenteditable='true']",
                    "//div[@aria-label='Write your prompt to Claude']",
                    "//p[@data-placeholder='How can I help you today?']",
                    "//textarea[@placeholder='Message Claude...']"
                ]
                
                for selector in input_selectors:
                    try:
                        input_element = self.driver.find_element(By.XPATH, selector)
                        if input_element.is_displayed():
                            self._update_progress(30, "已检测到对话界面，跳过模型选择")
                            return
                    except:
                        continue
            except:
                pass
            
            # 选择器列表，按优先级排序
            selectors = [
                # 最新版本的选择器
                "//div[contains(@class, 'card') and .//div[contains(text(), 'Claude')]]",
                "//div[contains(@class, 'card') and .//span[contains(text(), 'Claude')]]",
                "//div[contains(@class, 'model-option') and .//div[contains(text(), 'Claude')]]",
                "//div[contains(@class, 'model-card') and .//div[contains(text(), 'Claude')]]",
                "//div[contains(@class, 'model-card') and .//span[contains(text(), 'Claude')]]",
                
                # 以前版本的选择器
                "//div[contains(@class, 'n-card__content')]",
                "//span[contains(text(), 'Pro')]/ancestor::div[contains(@class, 'n-card__content')]",
                "//span[contains(text(), '空闲-推荐')]/ancestor::div[contains(@class, 'n-card__content')]",
                "//div[contains(@class, 'boxclass')]",
                "//div[contains(@class, 'pluscolor')]",
                
                # 备用选择器
                "//div[contains(text(), 'Claude')]",
                "//div[contains(@class, 'model') and contains(text(), 'Claude')]",
                "//div[contains(text(), 'Claude') or contains(text(), 'claude')]",
                "//button[contains(@class, 'model')]",
                "//h3[contains(text(), 'Claude')]/..",
                "//div[contains(@role, 'button')]",
                "//div[contains(@role, 'none')]"
            ]
            
            # 尝试每个选择器
            claude_models = []
            used_selector = ""
            for selector in selectors:
                try:
                    self._update_progress(30, f"使用选择器 {selector} 查找模型...")
                    # 使用更长的等待时间
                    elements = WebDriverWait(self.driver, 5).until(
                        EC.presence_of_all_elements_located((By.XPATH, selector))
                    )
                    if elements:
                        claude_models = elements
                        used_selector = selector
                        self._update_progress(31, f"找到 {len(claude_models)} 个可能的模型元素，使用选择器: {selector}")
                        break
                except:
                    continue
            
            if not claude_models:
                # 尝试截图记录当前页面状态
                try:
                    screenshot_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 
                                               "screenshot.png")
                    self.driver.save_screenshot(screenshot_path)
                    self._update_progress(32, f"无法找到模型，已保存页面截图到 {screenshot_path}")
                except:
                    pass
                
                # 尝试记录当前页面源码，以便进一步分析
                try:
                    page_source_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 
                                               "page_source.html")
                    with open(page_source_path, 'w', encoding='utf-8') as f:
                        f.write(self.driver.page_source)
                    self._update_progress(32, f"已保存页面源码到 {page_source_path}")
                except:
                    pass
                
                # 尝试检查是否已经在对话界面
                try:
                    # 最后尝试URL检查
                    current_url = self.driver.current_url
                    if "chat" in current_url or "conversation" in current_url:
                        self._update_progress(32, "URL检查显示可能已在对话界面，尝试继续...")
                        return
                except:
                    pass
                    
                raise Exception("找不到可用的Claude模型元素，请检查网站是否已更改")
            
            # 尝试选择模型
            model_selected = False
            for i, model in enumerate(claude_models):
                if not self._is_running:
                    break
                
                try:
                    # 尝试获取模型文本或描述元素
                    try:
                        # 输出模型HTML以便调试
                        model_html = self.driver.execute_script("return arguments[0].outerHTML;", model)
                        self._update_progress(33 + i, f"模型元素HTML: {model_html[:100]}...")
                        
                        # 尝试从HTML中解析模型名称
                        model_text = model.text or "未知模型"
                        if not model_text or model_text.strip() == "":
                            model_text = "未知模型 " + str(i+1)
                            
                    except:
                        model_text = f"未知模型 {i+1}"
                        
                    self._update_progress(33 + i, f"尝试选择模型: {model_text}...")
                    
                    # 尝试使用JavaScript点击，这通常更可靠
                    self.driver.execute_script("arguments[0].scrollIntoView(true);", model)
                    time.sleep(0.5)  # 等待滚动完成
                    
                    # 首先尝试点击模型卡片本身
                    self.driver.execute_script("arguments[0].click();", model)
                    time.sleep(1)  # 等待点击响应
                    
                    # 如果卡片点击无效，尝试查找卡片内的按钮或特定元素并点击
                    try:
                        inner_elements = [
                            ".//button",
                            ".//div[contains(@role, 'button')]",
                            ".//div[contains(@class, 'card')]",
                            ".//div[@tabindex='0']",
                            ".//div[contains(@class, 'clickable')]"
                        ]
                        
                        for inner_selector in inner_elements:
                            try:
                                inner_element = model.find_element(By.XPATH, inner_selector)
                                self.driver.execute_script("arguments[0].click();", inner_element)
                                self._update_progress(34 + i, f"点击内部元素: {inner_selector}")
                                time.sleep(1)  # 等待点击响应
                                break
                            except:
                                continue
                    except:
                        pass
                    
                    # 等待进入对话界面，尝试多个可能的输入框选择器
                    input_selectors = [
                        # 第二轮对话的新界面选择器 - 基于用户提供的HTML结构
                        "//div[@class='ProseMirror break-words max-w-[60ch]']",
                        "//div[@contenteditable='true' and @class='ProseMirror break-words max-w-[60ch]']",
                        "//div[@aria-label='Write your prompt to Claude']/div[@contenteditable='true']",
                        "//p[@data-placeholder='Reply to Claude...']/parent::div",
                        
                        # 新界面 - contenteditable div (通用选择器)
                        "//div[contains(@class, 'ProseMirror')]",
                        "//div[@contenteditable='true']",
                        "//div[@aria-label='Write your prompt to Claude']",
                        "//p[@data-placeholder='How can I help you today?']/parent::div",
                        "//p[contains(@data-placeholder, 'Reply to Claude')]/parent::div",
                        "//div[contains(@class, 'relative')]/div/div[@contenteditable='true']",
                        
                        # 旧界面 - textarea
                        "//textarea[@placeholder='Message Claude...']",
                        "//textarea[contains(@placeholder, 'Claude')]",
                        "//textarea[contains(@placeholder, 'Message')]",
                        "//textarea[@role='textbox']",
                        "//div[@role='textbox']",
                        "//textarea"
                    ]
                    
                    # 尝试每个输入框选择器
                    for input_selector in input_selectors:
                        try:
                            self._update_progress(35, f"检查输入框 {input_selector}...")
                            # 使用更长的等待时间
                            WebDriverWait(self.driver, 10).until(
                                EC.presence_of_element_located((By.XPATH, input_selector))
                            )
                            # 找到输入框，模型选择成功
                            self._update_progress(38, f"已选择模型: {model_text}")
                            model_selected = True
                            break
                        except:
                            continue
                    
                    if model_selected:
                        break
                    
                    # 如果依然未检测到输入框，检查URL是否已经改变
                    try:
                        current_url = self.driver.current_url
                        if "chat" in current_url or "conversation" in current_url:
                            self._update_progress(38, "URL检查显示已进入对话界面")
                            model_selected = True
                            break
                    except:
                        pass
                    
                except Exception as e:
                    self._update_progress(34, f"选择模型 {i+1} 失败: {str(e)}")
                    continue
            
            if not model_selected:
                # 再次尝试截图
                try:
                    screenshot_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 
                                               "selection_failed.png")
                    self.driver.save_screenshot(screenshot_path)
                    self._update_progress(39, f"选择失败，已保存截图到 {screenshot_path}")
                except:
                    pass
                    
                raise Exception("无法选择任何Claude模型，请检查网站是否已更改或尝试手动选择")
            
        except TimeoutException:
            raise Exception("选择Claude模型超时，请检查网络连接或网站是否已更改")
        except WebDriverException as e:
            raise Exception(f"选择Claude模型错误: {str(e)}")
        except Exception as e:
            raise Exception(f"选择Claude模型时发生未知错误: {str(e)}")
    
    def _conduct_conversations(self, initial_prompt: str) -> List[Dict[str, str]]:
        """
        进行多轮对话
        
        Args:
            initial_prompt: 初始提示词
            
        Returns:
            对话列表，每个对话包含prompt和response
            
        Raises:
            Exception: 如果对话过程中出错
        """
        conversations = []
        
        # 全局重试计数，跟踪整个对话过程的重试次数
        global_retry_count = 0
        max_global_retries = 3
        
        # 定义查找输入元素的函数，包含重试机制
        def find_input_element_with_retry(max_retries=3):
            """
            使用重试机制查找输入元素
            
            Returns:
                元组 (输入元素, 是否为新界面)
            """
            for retry in range(max_retries):
                try:
                    # 尝试多种输入框选择器
                    input_selectors = [
                        # 最新Claude界面选择器 - 基于错误信息提供的HTML结构
                        "//div[@contenteditable='true' and contains(@class,'ProseMirror')]",
                        "//div[@class='ProseMirror break-words max-w-[60ch]']",
                        "//p[@data-placeholder='Reply to Claude...']//ancestor::div[@contenteditable='true']",
                        "//div[@aria-label='Write your prompt to Claude']//div[@contenteditable='true']",
                        "//div[@contenteditable='true' and @translate='no' and @enterkeyhint='enter']",
                        
                        # 第二轮对话的新界面选择器
                        "//div[@contenteditable='true' and @class='ProseMirror break-words max-w-[60ch]']",
                        "//div[@aria-label='Write your prompt to Claude']/div[@contenteditable='true']",
                        "//p[@data-placeholder='Reply to Claude...']/parent::div",
                        
                        # 新界面 - contenteditable div (通用选择器)
                        "//div[contains(@class, 'ProseMirror')]",
                        "//div[@contenteditable='true']",
                        "//div[@aria-label='Write your prompt to Claude']",
                        "//p[@data-placeholder='How can I help you today?']/parent::div",
                        "//p[contains(@data-placeholder, 'Reply to Claude')]/parent::div",
                        "//div[contains(@class, 'relative')]/div/div[@contenteditable='true']",
                        
                        # 旧界面 - textarea
                        "//textarea[@placeholder='Message Claude...']",
                        "//textarea[contains(@placeholder, 'Claude')]",
                        "//textarea[contains(@placeholder, 'Message')]",
                        "//textarea[@role='textbox']",
                        "//div[@role='textbox']",
                        "//textarea"
                    ]
                    
                    # 尝试每个选择器
                    for selector in input_selectors:
                        try:
                            self._update_progress(51, f"尝试使用选择器查找输入框: {selector}")
                            elements = self.driver.find_elements(By.XPATH, selector)
                            
                            if elements:
                                # 找到元素，检查是否可见和可交互
                                for element in elements:
                                    if element.is_displayed():
                                        # 确认元素是否为contenteditable或textarea来判断界面类型
                                        is_new_interface = False
                                        try:
                                            is_contenteditable = self.driver.execute_script(
                                                "return arguments[0].getAttribute('contenteditable') === 'true';", 
                                                element
                                            )
                                            is_new_interface = is_contenteditable
                                        except:
                                            is_new_interface = "ProseMirror" in selector or "contenteditable" in selector
                                        
                                        # 保存截图以供诊断
                                        try:
                                            screenshots_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "screenshots")
                                            os.makedirs(screenshots_dir, exist_ok=True)
                                            self.driver.save_screenshot(os.path.join(screenshots_dir, f"input_element_found_{int(time.time())}.png"))
                                            self._update_progress(52, f"已保存截图")
                                        except Exception as e:
                                            self._update_progress(52, f"保存截图失败: {str(e)}")
                                        
                                        self._update_progress(52, f"找到输入框: {'新界面' if is_new_interface else '旧界面'}")
                                        return element, is_new_interface
                        except Exception as e:
                            self._update_progress(51, f"使用选择器 {selector} 查找失败: {str(e)}")
                            continue
                    
                    # 检查URL是否包含特定字符串，这可能有助于确定界面类型
                    current_url = self.driver.current_url
                    if "claude.ai/chat" in current_url:
                        self._update_progress(52, "检测到Claude聊天URL，但未找到输入框，尝试查找页面源码中的线索")
                        
                        # 保存页面源码以供诊断
                        try:
                            logs_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "logs")
                            os.makedirs(logs_dir, exist_ok=True)
                            with open(os.path.join(logs_dir, f"page_source_{int(time.time())}.html"), "w", encoding="utf-8") as f:
                                f.write(self.driver.page_source)
                            self._update_progress(52, f"已保存页面源码")
                        except Exception as e:
                            self._update_progress(52, f"保存页面源码失败: {str(e)}")
                    
                    # 如果遍历所有选择器都未找到元素，进行重试
                    if retry < max_retries - 1:
                        self._update_progress(52, f"未找到输入框，等待1秒后重试 ({retry+1}/{max_retries})")
                        time.sleep(1)
                    
                except Exception as e:
                    if retry < max_retries - 1:
                        self._update_progress(52, f"查找输入框时出错，重试中 ({retry+1}/{max_retries}): {str(e)}")
                        time.sleep(1)
            
            # 所有重试都失败，保存页面截图
            try:
                screenshots_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "screenshots")
                os.makedirs(screenshots_dir, exist_ok=True)
                self.driver.save_screenshot(os.path.join(screenshots_dir, f"input_element_not_found_{int(time.time())}.png"))
            except:
                pass
                
            # 获取当前页面HTML结构用于诊断
            try:
                page_html = self.driver.page_source
                error_message = "找不到输入框，可能网站结构已更改。"
                
                # 检查是否存在错误信息中提到的结构，并提供匹配信息
                if "ProseMirror break-words max-w-[60ch]" in page_html:
                    error_message += " 输入框div:<div class=\"relative\"><div aria-label=\"Write your prompt to Claude\" class=\"max-h-96 w-full overflow-y-auto break-words min-h-[1.5rem]\"><div contenteditable=\"true\" translate=\"no\" enterkeyhint=\"enter\" tabindex=\"0\" class=\"ProseMirror break-words max-w-[60ch]\"><p data-placeholder=\"Reply to Claude...\" class=\"is-empty is-editor-empty before:!text-text-500 before:whitespace-nowrap\"><br class=\"ProseMirror-trailingBreak\"></p></div></div></div>"
                
                # 抛出详细的异常
                raise Exception(error_message)
            except Exception as e:
                # 所有重试都失败
                self._update_progress(53, "多次尝试后未能找到输入框")
                return None, False
            
        # 辅助函数：查找并点击发送按钮
        def find_and_click_send_button():
            """查找并点击发送按钮"""
            send_button_selectors = [
                # 最新版Claude界面发送按钮选择器 - 基于精确结构
                "//button[@class='inline-flex items-center justify-center relative shrink-0 can-focus select-none disabled:pointer-events-none disabled:opacity-50 disabled:shadow-none disabled:drop-shadow-none transition-all rounded-lg active:scale-[0.98] will-change-transform min-w-8 h-8 md:h-10 md:min-w-10' and @aria-label='Send message to Claude' and @type='button']",
                "//button[contains(@class, 'rounded-lg') and @aria-label='Send message to Claude']",
                "//button[@aria-label='Send message to Claude']",
                "//button[.//svg[contains(@viewBox, '0 0 24 24')]]",
                
                # 基于相对位置的发送按钮选择器
                "//div[contains(@aria-label, 'Write your prompt to Claude')]/following-sibling::button",
                "//div[contains(@class, 'ProseMirror')]/ancestor::div[contains(@class, 'relative')]/following-sibling::button",
                "//div[contains(@class, 'relative')]/following-sibling::button[1]",
                "//div[@contenteditable='true']/ancestor::div/following-sibling::button",
                
                # 第二轮对话中的发送按钮选择器
                "//div[contains(@class, 'ProseMirror')]/ancestor::div/following-sibling::button",
                
                # 通用发送按钮选择器
                "//button[@aria-label='Send message']",
                "//button[contains(@class, 'send')]",
                "//button[contains(@class, 'submit')]",
                "//button[.//svg[contains(@class, 'send')]]",
                "//button[.//span[contains(text(), '发送')]]",
                "//button[contains(@title, 'Send')]",
                "//button[contains(@title, '发送')]"
            ]
            
            # 增强版查找按钮函数
            for selector in send_button_selectors:
                try:
                    self._update_progress(56, f"尝试查找发送按钮: {selector}")
                    buttons = self.driver.find_elements(By.XPATH, selector)
                    
                    if buttons:
                        for button in buttons:
                            # 验证按钮是否可见和可点击
                            if button.is_displayed():
                                try:
                                    # 使用更可靠的方式确认按钮位置和状态
                                    self._update_progress(56, "找到按钮，准备点击...")
                                    
                                    # 先尝试滚动到按钮位置
                                    self.driver.execute_script(
                                        "arguments[0].scrollIntoView({block: 'center'});", 
                                        button
                                    )
                                    time.sleep(0.3)
                                    
                                    # 保存发送按钮的截图以便诊断
                                    try:
                                        screenshots_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "screenshots")
                                        os.makedirs(screenshots_dir, exist_ok=True)
                                        # 高亮按钮位置并保存截图
                                        self.driver.execute_script("""
                                            let oldBorder = arguments[0].style.border;
                                            let oldBackground = arguments[0].style.backgroundColor;
                                            arguments[0].style.border = '2px solid red';
                                            arguments[0].style.backgroundColor = 'yellow';
                                            return [oldBorder, oldBackground];
                                        """, button)
                                        self.driver.save_screenshot(os.path.join(screenshots_dir, f"send_button_found_{int(time.time())}.png"))
                                        # 恢复按钮样式
                                        self.driver.execute_script("""
                                            arguments[0].style.border = arguments[1][0];
                                            arguments[0].style.backgroundColor = arguments[1][1];
                                        """, button, ["", ""])
                                    except Exception as e:
                                        self._update_progress(56, f"截图失败: {str(e)}")
                                        
                                    # 检查按钮是否被禁用
                                    is_disabled = self.driver.execute_script("""
                                        return arguments[0].disabled || 
                                               arguments[0].getAttribute('aria-disabled') === 'true' ||
                                               arguments[0].classList.contains('disabled') ||
                                               arguments[0].getAttribute('disabled') !== null;
                                    """, button)
                                    
                                    if is_disabled:
                                        self._update_progress(56, "发送按钮处于禁用状态，检查输入框内容...")
                                        continue
                                    
                                    # 尝试不同的点击方法
                                    try:
                                        # 先尝试JavaScript点击
                                        self.driver.execute_script("arguments[0].click();", button)
                                        self._update_progress(56, "使用JavaScript成功点击发送按钮")
                                        return True
                                    except:
                                        # 如果JavaScript点击失败，尝试常规点击
                                        button.click()
                                        self._update_progress(56, "使用常规方法成功点击发送按钮")
                                        return True
                                        
                                except Exception as e:
                                    self._update_progress(56, f"点击按钮时出错: {str(e)}，尝试下一个按钮")
                                    continue
                except Exception as e:
                    self._update_progress(56, f"使用选择器 {selector} 查找按钮失败: {str(e)}")
                    continue
            
            # 如果没有找到按钮，尝试再次保存截图以便分析
            try:
                screenshots_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "screenshots")
                os.makedirs(screenshots_dir, exist_ok=True)
                self.driver.save_screenshot(os.path.join(screenshots_dir, f"send_button_not_found_{int(time.time())}.png"))
            except:
                pass
            
            # 尝试直接按回车键
            input_element = None
            try:
                # 尝试查找当前输入框
                for input_selector in [
                    "//div[@contenteditable='true']",
                    "//div[contains(@class, 'ProseMirror')]",
                    "//div[@aria-label='Write your prompt to Claude']/div",
                    "//textarea[@placeholder='Message Claude...']"
                ]:
                    try:
                        elements = self.driver.find_elements(By.XPATH, input_selector)
                        if elements:
                            for element in elements:
                                if element.is_displayed():
                                    input_element = element
                                    break
                            if input_element:
                                break
                    except:
                        continue
                        
                if input_element:
                    self._update_progress(56, "找不到发送按钮，尝试按回车键发送...")
                    input_element.send_keys(Keys.RETURN)
                    return True
            except:
                pass
                
            raise Exception("找不到发送按钮")
            
        # 定义发送消息的函数，包含重试机制
        def send_message_with_retry(input_element, max_retries=3):
            """
            使用重试机制发送消息
            
            Args:
                input_element: 输入元素
                
            Returns:
                是否成功发送
            """
            for retry in range(max_retries):
                try:
                    # 尝试使用不同的发送方式
                    send_methods = [
                        # 方法1: 查找发送按钮并点击
                        lambda: find_and_click_send_button(),
                        
                        # 方法2: 使用Enter键发送
                        lambda: input_element.send_keys(Keys.RETURN),
                        
                        # 方法3: 使用JavaScript模拟Enter键
                        lambda: self.driver.execute_script("""
                            var event = new KeyboardEvent('keydown', {
                                key: 'Enter',
                                code: 'Enter',
                                keyCode: 13,
                                which: 13,
                                bubbles: true,
                                cancelable: true
                            });
                            arguments[0].dispatchEvent(event);
                        """, input_element)
                    ]
                    
                    # 发送前保存截图，了解当前状态
                    try:
                        screenshots_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "screenshots")
                        os.makedirs(screenshots_dir, exist_ok=True)
                        self.driver.save_screenshot(os.path.join(screenshots_dir, f"before_send_message_{int(time.time())}.png"))
                    except:
                        pass
                    
                    # 尝试每种发送方法
                    for i, send_method in enumerate(send_methods):
                        try:
                            self._update_progress(56, f"尝试使用发送方法 {i+1}/{len(send_methods)} (第{retry+1}次重试)")
                            send_method()
                            
                            # 等待短暂时间，确认是否开始处理
                            time.sleep(1)
                            
                            # 方法1：检查是否有输入指示器出现，表示发送成功
                            typing_indicators = [
                                "//div[contains(@class, 'typing-indicator')]", 
                                "//div[contains(@class, 'loading')]",
                                "//div[contains(@class, 'message-loading')]",
                                "//div[contains(@class, 'thinking')]",
                                "//div[contains(@class, 'spinner')]",
                                "//div[contains(@class, 'typing')]"
                            ]
                            
                            for indicator in typing_indicators:
                                try:
                                    if self.driver.find_elements(By.XPATH, indicator):
                                        self._update_progress(57, f"检测到指示器: {indicator}，消息已成功发送")
                                        return True
                                except:
                                    continue
                                    
                            # 方法2：检查输入框是否被清空（有些界面发送后会自动清空输入框）
                            try:
                                # 检查输入框内容是否被清空
                                current_text = ''
                                try:
                                    current_text = self.driver.execute_script("return arguments[0].textContent", input_element)
                                except:
                                    try:
                                        current_text = self.driver.execute_script("return arguments[0].value", input_element)
                                    except:
                                        pass
                                
                                if current_text is None or current_text.strip() == '':
                                    self._update_progress(57, "输入框已被清空，消息可能已发送")
                                    
                                    # 保存消息发送后的截图
                                    try:
                                        self.driver.save_screenshot(os.path.join(screenshots_dir, f"after_send_clear_input_{int(time.time())}.png"))
                                    except:
                                        pass
                                    
                                    # 额外等待几秒，确认回复开始
                                    time.sleep(3)
                                    return True
                            except Exception as e:
                                self._update_progress(57, f"检查输入框清空状态时出错: {str(e)}")
                            
                            # 方法3：检查输入框是否不再可编辑（有些界面发送后会暂时禁用输入框）
                            try:
                                is_disabled = False
                                try:
                                    is_disabled = self.driver.execute_script("""
                                        return arguments[0].disabled || 
                                               arguments[0].getAttribute('contenteditable') === 'false' ||
                                               arguments[0].classList.contains('disabled');
                                    """, input_element)
                                except:
                                    pass
                                
                                if is_disabled:
                                    self._update_progress(57, "输入框已被禁用，消息可能已发送")
                                    return True
                            except Exception as e:
                                self._update_progress(57, f"检查输入框禁用状态时出错: {str(e)}")
                                
                            # 方法4：检查是否出现了新的消息元素
                            try:
                                message_selectors = [
                                    "//div[contains(@class, 'grid-cols-1') and contains(@class, 'grid')]",
                                    "//div[contains(@class, 'message-content')]",
                                    "//div[contains(@class, 'assistant-message')]",
                                    "//div[contains(@class, 'markdown')]"
                                ]
                                
                                # 记录发送前消息元素数量
                                message_counts_before = {}
                                for selector in message_selectors:
                                    try:
                                        elements = self.driver.find_elements(By.XPATH, selector)
                                        message_counts_before[selector] = len(elements)
                                    except:
                                        message_counts_before[selector] = 0
                                
                                # 等待几秒
                                time.sleep(3)
                                
                                # 检查是否有新消息出现
                                for selector in message_selectors:
                                    try:
                                        elements = self.driver.find_elements(By.XPATH, selector)
                                        if len(elements) > message_counts_before[selector]:
                                            self._update_progress(57, f"检测到新消息元素: {selector}，消息已发送")
                                            return True
                                    except:
                                        continue
                            except Exception as e:
                                self._update_progress(57, f"检查新消息出现时出错: {str(e)}")
                                
                            # 如果上述检测方法都未能确认发送成功，但也没有明确的错误，我们假设消息已发送
                            # 这是一个折衷方案，避免误判发送失败
                            self._update_progress(57, "无法明确确认消息发送状态，假设已成功发送")
                            
                            # 保存当前状态的截图
                            try:
                                self.driver.save_screenshot(os.path.join(screenshots_dir, f"assumed_send_success_{int(time.time())}.png"))
                            except:
                                pass
                                
                            return True
                            
                        except Exception as e:
                            self._update_progress(56, f"发送方法 {i+1} 失败: {str(e)}")
                            
                            # 保存方法失败的截图
                            try:
                                screenshots_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "screenshots")
                                os.makedirs(screenshots_dir, exist_ok=True)
                                self.driver.save_screenshot(os.path.join(screenshots_dir, f"send_method_{i+1}_failed_{int(time.time())}.png"))
                            except:
                                pass
                                
                            continue
                    
                    # 如果所有方法都失败，但尚未达到最大重试次数，则重试
                    if retry < max_retries - 1:
                        self._update_progress(57, f"所有发送方法均失败，重试中 ({retry+1}/{max_retries})")
                        time.sleep(2)  # 增加等待时间
                
                except Exception as e:
                    if retry < max_retries - 1:
                        self._update_progress(57, f"发送消息过程中出错，重试中 ({retry+1}/{max_retries}): {str(e)}")
                        time.sleep(2)  # 增加等待时间
            
            # 所有重试都失败，保存最终状态截图
            try:
                screenshots_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "screenshots")
                os.makedirs(screenshots_dir, exist_ok=True)
                self.driver.save_screenshot(os.path.join(screenshots_dir, f"all_send_methods_failed_{int(time.time())}.png"))
            except:
                pass
                
            # 所有重试都失败，记录输入框信息
            try:
                error_message = "多次尝试后未能发送消息"
                
                # 获取当前输入框的信息，帮助诊断问题
                if input_element:
                    input_html = self.driver.execute_script("return arguments[0].outerHTML;", input_element)
                    parent_html = self.driver.execute_script("return arguments[0].parentNode.outerHTML;", input_element)
                    error_message = f"{error_message}。输入框的div:{input_html}"
            except:
                error_message = "多次尝试后未能发送消息，且无法获取输入框信息"
                
            self._update_progress(57, error_message)
            return False
        
        while global_retry_count < max_global_retries:
            try:
                # 执行第一轮对话
                self._update_progress(50, f"正在进行第1轮对话... (全局尝试: {global_retry_count+1}/{max_global_retries})")
                
                # 使用重试机制查找输入元素
                input_element, is_new_interface = find_input_element_with_retry()
                
                if not input_element:
                    # 尝试刷新页面
                    if global_retry_count < max_global_retries - 1:
                        self._update_progress(52, f"找不到输入框，尝试刷新页面 ({global_retry_count+1}/{max_global_retries})")
                        self.driver.refresh()
                        time.sleep(3)
                        global_retry_count += 1
                        continue
                    
                    # 最终尝试失败，记录页面状态并抛出异常
                    try:
                        screenshot_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 
                                                   "input_not_found.png")
                        self.driver.save_screenshot(screenshot_path)
                        self._update_progress(53, f"找不到输入框，已保存截图到 {screenshot_path}")
                    except:
                        pass
                    
                    raise Exception("找不到输入框，可能网站结构已更改")
                
                # 输入提示词 - 针对新旧界面使用不同方法
                self._update_progress(54, "输入提示词...")
                
                # 清理提示词，移除非BMP Unicode字符
                cleaned_prompt = clean_unicode_text(initial_prompt)
                if cleaned_prompt != initial_prompt:
                    self._update_progress(54, "检测到非BMP Unicode字符，已进行清理")
                
                # 检测是否包含特殊格式
                has_special_format = any([
                    '```' in cleaned_prompt,  # 代码块
                    '|' in cleaned_prompt,    # 表格
                    '[' in cleaned_prompt,    # 方括号标记
                    ']' in cleaned_prompt,
                    '<' in cleaned_prompt,    # HTML标签或箭头
                    '>' in cleaned_prompt,
                    '*' in cleaned_prompt,    # 星号标记
                    '#' in cleaned_prompt,    # 标题或井号
                    '- ' in cleaned_prompt,   # 列表
                    '1. ' in cleaned_prompt,  # 有序列表
                    '=' in cleaned_prompt,    # 赋值符号
                    '/' in cleaned_prompt,    # 命令前缀
                    '"""' in cleaned_prompt,  # 多行字符串
                    'Thinking' in cleaned_prompt  # 特殊指令
                ])
                
                # 尝试重新检查输入元素是否仍然有效
                try:
                    self.driver.execute_script("return arguments[0].isConnected", input_element)
                except StaleElementReferenceException:
                    # 如果元素已经失效，重试整个过程
                    self._update_progress(55, "输入框引用已过期，重新开始...")
                    global_retry_count += 1
                    continue
                
                # 尝试使用重试机制输入文本
                def input_text_with_retry(element, text, max_retries=3):
                    """使用重试机制输入文本"""
                    for retry in range(max_retries):
                        try:
                            if is_new_interface:
                                # 新界面 - 使用JavaScript设置内容和触发事件
                                self._update_progress(55, f"使用新界面输入方法 (尝试 {retry+1}/{max_retries})...")
                                
                                # 检查是否为contenteditable的div元素
                                is_contenteditable = False
                                try:
                                    is_contenteditable = self.driver.execute_script(
                                        "return arguments[0].getAttribute('contenteditable') === 'true';", 
                                        element
                                    )
                                except:
                                    pass
                                
                                if is_contenteditable:
                                    # 直接处理contenteditable的div
                                    self._update_progress(55, "检测到contenteditable输入框，使用专用方法...")
                                    try:
                                        # 先聚焦并清空内容
                                        self.driver.execute_script("""
                                            arguments[0].focus();
                                            arguments[0].innerHTML = '<p><br></p>';
                                        """, element)
                                        time.sleep(0.3)
                                        
                                        # 对特殊格式内容采用更安全的输入方式
                                        if has_special_format:
                                            # 使用更保守的方式，原样保留格式
                                            self._update_progress(55, "检测到特殊格式，使用增强型输入方法...")
                                            
                                            # 将纯文本转换为HTML格式，保留换行符
                                            paragraphs = text.split('\n')
                                            html_content = ''
                                            in_code_block = False
                                            pre_open = False
                                            
                                            for para in paragraphs:
                                                # 处理代码块开始和结束
                                                if para.strip().startswith('```'):
                                                    if in_code_block:
                                                        html_content += '</code></pre>\n<p><br></p>'
                                                        in_code_block = False
                                                        pre_open = False
                                                    else:
                                                        html_content += '<pre><code>'
                                                        in_code_block = True
                                                        pre_open = True
                                                    continue
                                                    
                                                # 处理代码块内容
                                                if in_code_block:
                                                    # 保留代码块内的内容，仅转义HTML特殊字符
                                                    safe_para = para.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
                                                    html_content += safe_para + '\n'
                                                    continue
                                                    
                                                # 处理普通段落
                                                if para.strip() == '':
                                                    html_content += '<p><br></p>'
                                                else:
                                                    # 安全处理HTML特殊字符，但保留格式标记和中文字符
                                                    safe_para = para.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
                                                    
                                                    # 保留表格结构、列表和中文文本
                                                    if '|' in safe_para:
                                                        html_content += f'<p>{safe_para}</p>'
                                                    elif para.startswith('- ') or re.match(r'^\d+\.\s', para):
                                                        # 处理列表项
                                                        html_content += f'<p>{safe_para}</p>'
                                                    else:
                                                        html_content += f'<p>{safe_para}</p>'
                                            
                                            # 确保代码块关闭
                                            if pre_open:
                                                html_content += '</code></pre>\n<p><br></p>'
                                            
                                            # 使用安全的JS方法注入内容，特别处理中文字符
                                            js_inject_code = """
                                                try {
                                                    arguments[0].innerHTML = `""" + html_content + """`;
                                                    
                                                    // 创建并分发输入事件
                                                    var evt = new InputEvent('input', {
                                                        bubbles: true,
                                                        cancelable: true,
                                                    });
                                                    arguments[0].dispatchEvent(evt);
                                                    
                                                    // 创建并分发更改事件
                                                    var changeEvt = new Event('change', {
                                                        bubbles: true
                                                    });
                                                    arguments[0].dispatchEvent(changeEvt);
                                                    return true;
                                                } catch(e) {
                                                    return e.toString();
                                                }
                                            """
                                            
                                            # 执行JS代码并检查结果
                                            result = self.driver.execute_script(js_inject_code, element)
                                            if result != True:
                                                raise Exception(f"JS注入失败: {result}")
                                            
                                            # 确保焦点在编辑器上
                                            self.driver.execute_script("arguments[0].focus();", element)
                                        else:
                                            # 对于普通文本，特别是中文文本，使用更安全的HTML注入方式
                                            # 将文本按段落分割，并为每个段落创建p标签
                                            paragraphs = text.split('\n')
                                            html_content = ''
                                            
                                            for para in paragraphs:
                                                if para.strip() == '':
                                                    html_content += '<p><br></p>'
                                                else:
                                                    # 安全处理HTML特殊字符，确保中文字符不受影响
                                                    safe_para = para.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
                                                    html_content += f'<p>{safe_para}</p>'
                                            
                                            # 使用较为直接的JS注入方式
                                            js_code = """
                                                try {
                                                    arguments[0].innerHTML = `""" + html_content + """`;
                                                    
                                                    // 创建并分发input事件
                                                    var inputEvent = new Event('input', { bubbles: true });
                                                    arguments[0].dispatchEvent(inputEvent);
                                                    
                                                    // 创建并分发change事件
                                                    var changeEvent = new Event('change', { bubbles: true });
                                                    arguments[0].dispatchEvent(changeEvent);
                                                    return true;
                                                } catch(e) {
                                                    return e.toString();
                                                }
                                            """
                                            
                                            # 执行JS代码并检查结果
                                            result = self.driver.execute_script(js_code, element)
                                            if result != True:
                                                raise Exception(f"JS注入失败: {result}")
                                        
                                        return True
                                    except Exception as e:
                                        # 记录错误，如果不是最后一次尝试则继续
                                        if retry < max_retries - 1:
                                            self._update_progress(55, f"contenteditable输入出错，正在重试 ({retry+1}/{max_retries}): {str(e)}")
                                            time.sleep(1)
                                            continue
                                        # 如果是最后一次尝试，回退到备用方法
                                        is_contenteditable = False
                                
                                if not is_contenteditable:
                                    # 先聚焦并点击输入框
                                    self.driver.execute_script("arguments[0].click();", element)
                                    time.sleep(0.5)
                                    
                                    # 对特殊格式内容采用字符串方式处理
                                    if has_special_format:
                                        # 转义所有可能引起问题的字符
                                        js_safe_prompt = text.replace('\\', '\\\\').replace('`', '\\`').replace('$', '\\$')
                                        # 使用反引号字符串允许多行
                                        js_code = f"""
                                            try {{
                                                arguments[0].textContent = `{js_safe_prompt}`;
                                                arguments[0].dispatchEvent(new Event('input', {{ bubbles: true }}));
                                                return true;
                                            }} catch(e) {{
                                                return e.toString();
                                            }}
                                        """
                                        result = self.driver.execute_script(js_code, element)
                                        if result != True:
                                            raise Exception(f"JS文本设置失败: {result}")
                                    else:
                                        # 使用JavaScript插入文本内容
                                        js_code = f"""
                                            try {{
                                                arguments[0].textContent = {repr(text)};
                                                arguments[0].dispatchEvent(new Event('input', {{ bubbles: true }}));
                                                return true;
                                            }} catch(e) {{
                                                return e.toString();
                                            }}
                                        """
                                        result = self.driver.execute_script(js_code, element)
                                        if result != True:
                                            raise Exception(f"JS文本设置失败: {result}")
                                    
                                    time.sleep(0.5)
                                    
                                    # 检查内容是否输入成功
                                    actual_content = self.driver.execute_script("return arguments[0].textContent;", element)
                                    if not actual_content:
                                        if retry < max_retries - 1:
                                            self._update_progress(55, f"文本输入失败，正在重试 ({retry+1}/{max_retries})")
                                            time.sleep(1)
                                            continue
                                        else:
                                            # 最后一次尝试，使用键盘输入作为备用
                                            element.send_keys(text)
                                
                                return True
                            else:
                                # 旧界面 - 直接使用send_keys方法
                                element.clear()
                                element.send_keys(text)
                                return True
                        
                        except StaleElementReferenceException as e:
                            if retry < max_retries - 1:
                                self._update_progress(55, f"元素引用过期，正在重试 ({retry+1}/{max_retries}): {str(e)}")
                                time.sleep(1)
                            else:
                                return False
                        except Exception as e:
                            if retry < max_retries - 1:
                                self._update_progress(55, f"输入文本时出错，正在重试 ({retry+1}/{max_retries}): {str(e)}")
                                time.sleep(1)
                            else:
                                return False
                    
                    return False
                
                # 尝试输入文本
                input_success = input_text_with_retry(input_element, cleaned_prompt)
                
                if not input_success:
                    # 如果输入失败，重新开始整个过程
                    if global_retry_count < max_global_retries - 1:
                        self._update_progress(56, "输入文本失败，将重新开始整个过程")
                        global_retry_count += 1
                        time.sleep(2)
                        continue
                    else:
                        raise Exception("多次尝试输入文本失败")
                
                # 使用重试机制发送消息
                send_success = send_message_with_retry(input_element)
                if not send_success:
                    # 如果发送失败，重新开始整个过程
                    if global_retry_count < max_global_retries - 1:
                        self._update_progress(57, "发送消息失败，将重新开始整个过程")
                        global_retry_count += 1
                        time.sleep(2)
                        continue
                    else:
                        raise Exception("多次尝试发送消息失败")
                
                try:
                    # 等待响应完成
                    self._update_progress(58, "等待Claude回复中...")
                    self._wait_for_response()
                    
                    # 获取第一轮对话响应
                    self._update_progress(60, "获取Claude回复...")
                    response = self._get_latest_response()
                    
                    # 检查响应是否有效
                    if response and len(response) > 10:  # 简单验证，确保不是空响应
                        conversations.append({"prompt": initial_prompt, "response": response})
                        break  # 成功获取响应，退出重试循环
                    else:
                        if global_retry_count < max_global_retries - 1:
                            self._update_progress(60, f"响应内容无效，将重新开始整个过程 ({global_retry_count+1}/{max_global_retries})")
                            global_retry_count += 1
                            time.sleep(2)
                            continue
                        else:
                            raise Exception("多次尝试获取有效响应失败")
                            
                except (TimeoutException, StaleElementReferenceException) as e:
                    if global_retry_count < max_global_retries - 1:
                        self._update_progress(59, f"等待或获取响应时出错，将重新开始整个过程 ({global_retry_count+1}/{max_global_retries}): {str(e)}")
                        global_retry_count += 1
                        time.sleep(2)
                        continue
                    else:
                        raise Exception(f"多次尝试等待或获取响应失败: {str(e)}")
            
            except Exception as e:
                if global_retry_count < max_global_retries - 1:
                    self._update_progress(50, f"对话过程中出错，将重新开始 ({global_retry_count+1}/{max_global_retries}): {str(e)}")
                    global_retry_count += 1
                    time.sleep(2)
                    continue
                else:
                    raise Exception(f"对话过程出错，已尝试 {max_global_retries} 次: {str(e)}")
                    
        # 如果已经成功获取第一轮对话响应，则继续进行后续对话
        if conversations:
            response = conversations[0]["response"]
            
            # 执行后续对话
            progress_increment = 30 / max(1, self.iterations - 1)
            for i in range(1, self.iterations):
                # 检查线程是否被要求停止
                if not self._is_running:
                    break
                
                # 更新进度
                base_progress = 60
                progress = base_progress + int(i * progress_increment)
                self._update_progress(progress, f"正在进行第{i+1}轮对话...")
                
                # 生成后续提示词
                self._update_progress(progress + 1, "生成后续提示词...")
                follow_up = generate_follow_up_prompt(i-1, response, self.follow_up_prompts)
                
                # 清理提示词，移除非BMP Unicode字符
                cleaned_follow_up = clean_unicode_text(follow_up)
                if cleaned_follow_up != follow_up:
                    self._update_progress(progress + 1, "检测到非BMP Unicode字符，已进行清理")
                
                # 给Claude一些休息时间，确保第二轮对话界面已更新
                self._update_progress(progress + 2, "等待Claude界面准备就绪...")
                time.sleep(2)
                
                # 重新获取输入元素 - 第二轮对话可能有不同的输入框
                self._update_progress(progress + 2, "重新查找第二轮对话的输入框...")
                input_element, is_new_interface = find_input_element_with_retry()
                if not input_element:
                    # 尝试刷新页面后重试
                    self._update_progress(progress + 2, "找不到第二轮对话输入框，尝试刷新页面...")
                    self.driver.refresh()
                    time.sleep(3)
                    input_element, is_new_interface = find_input_element_with_retry()
                    if not input_element:
                        raise Exception(f"第{i+1}轮对话无法找到输入框")
                
                # 输入后续提示词
                self._update_progress(progress + 3, "输入后续提示词...")
                self._update_progress(progress + 3, f"使用{'新' if is_new_interface else '旧'}界面输入方法")
                
                # 针对第二轮对话的特殊处理
                try:
                    # 先检查输入框是否为空，如果不为空则清空
                    if is_new_interface:
                        # 检查是否有文本
                        current_text = self.driver.execute_script("return arguments[0].textContent", input_element)
                        if current_text and current_text.strip():
                            # 清空输入框
                            self.driver.execute_script("""
                                arguments[0].innerHTML = '<p><br></p>';
                                arguments[0].dispatchEvent(new Event('input', { bubbles: true }));
                            """, input_element)
                            time.sleep(0.5)
                except Exception as e:
                    self._update_progress(progress + 3, f"清空输入框失败: {str(e)}")
                
                # 使用重试机制输入文本
                input_success = input_text_with_retry(input_element, cleaned_follow_up)
                if not input_success:
                    raise Exception(f"第{i+1}轮对话无法输入文本")
                
                # 发送提示词
                self._update_progress(progress + 4, "发送后续提示词...")
                send_success = send_message_with_retry(input_element)
                if not send_success:
                    raise Exception(f"第{i+1}轮对话无法发送消息")
                
                # 等待响应完成
                self._update_progress(progress + 5, "等待Claude回复中...")
                self._wait_for_response()
                
                # 获取响应
                self._update_progress(progress + 6, "获取Claude回复...")
                response = self._get_latest_response()
                conversations.append({"prompt": follow_up, "response": response})
                
            return conversations
        else:
            raise Exception("无法获取对话响应，请检查网络连接和网站状态")
            
        return conversations
    
    def _wait_for_response(self) -> None:
        """
        等待Claude响应完成
        
        Raises:
            TimeoutException: 如果等待超时
        """
        try:
            # 定义可能的正在输入指示器选择器
            typing_indicators = [
                "//div[contains(@class, 'typing-indicator')]",
                "//div[contains(@class, 'loading')]",
                "//div[contains(@class, 'message-loading')]",
                "//div[contains(@class, 'thinking')]",
                "//div[contains(@class, 'spinner')]",
                "//div[contains(@class, 'typing')]"
            ]
            
            # 增加重试计数和最大尝试次数
            max_attempts = 3
            attempt = 0
            while attempt < max_attempts:
                try:
                    # 等待任意一个输入指示器出现（开始回复）
                    found_indicator = False
                    for indicator in typing_indicators:
                        try:
                            self._update_progress(59, f"等待回复开始，检查指示器: {indicator}")
                            WebDriverWait(self.driver, 5).until(
                                EC.presence_of_element_located((By.XPATH, indicator))
                            )
                            found_indicator = True
                            self._update_progress(59, f"找到指示器: {indicator}，Claude正在回复")
                            break
                        except:
                            continue
                            
                    if not found_indicator:
                        # 如果没有找到指示器，可能是界面没有明显的加载状态
                        # 尝试等待几秒，观察新消息出现
                        self._update_progress(59, "未找到明确的输入指示器，等待响应...")
                        time.sleep(5)
                    
                    # 等待所有可能的输入指示器消失（回复完成）
                    max_wait_time = 120  # 最长等待2分钟
                    start_time = time.time()
                    
                    while True:
                        if time.time() - start_time > max_wait_time:
                            raise TimeoutException("等待响应完成超时")
                        
                        # 检查所有指示器是否都已消失
                        all_gone = True
                        for indicator in typing_indicators:
                            try:
                                # 检查是否有任何一个指示器仍然存在
                                indicator_elements = self.driver.find_elements(By.XPATH, indicator)
                                if indicator_elements and indicator_elements[0].is_displayed():
                                    all_gone = False
                                    self._update_progress(59, f"Claude仍在回复，指示器: {indicator}")
                                    break
                            except StaleElementReferenceException:
                                # 如果元素引用过期，重新查找
                                self._update_progress(59, "指示器引用已过期，重新检查...")
                                time.sleep(1)
                                continue
                            except:
                                pass
                        
                        # 新增：检查上传图标是否出现，表示Claude已完成响应并进入空闲状态
                        upload_icon_found = False
                        try:
                            # 检查是否存在上传图标SVG（上箭头）
                            upload_icon_selectors = [
                                # 基于用户提供的SVG路径
                                "//svg[contains(@viewBox, '0 0 256 256')]/path[contains(@d, 'M208.49,120.49a12,12,0,0,1-17,0L140,69V216')]",
                                "//svg[contains(@width, '16') and contains(@height, '16')]/path[contains(@d, 'M208.49,120.49')]",
                                # 通用上传图标选择器
                                "//button[contains(@class, 'upload') or contains(@aria-label, 'upload')]//svg",
                                "//svg[contains(@class, 'upload-icon')]",
                                # 通过父元素定位
                                "//div[contains(@class, 'input-area') or contains(@class, 'compose')]//svg[contains(@viewBox, '0 0 256 256')]"
                            ]
                            
                            for icon_selector in upload_icon_selectors:
                                icons = self.driver.find_elements(By.XPATH, icon_selector)
                                if icons and any(icon.is_displayed() for icon in icons):
                                    upload_icon_found = True
                                    self._update_progress(59, "检测到上传图标出现，表示Claude已完成响应")
                                    
                                    # 保存截图，记录图标出现状态
                                    try:
                                        screenshots_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "screenshots")
                                        os.makedirs(screenshots_dir, exist_ok=True)
                                        self.driver.save_screenshot(os.path.join(screenshots_dir, f"upload_icon_found_{int(time.time())}.png"))
                                    except:
                                        pass
                                        
                                    break
                        except:
                            pass
                        
                        if all_gone or upload_icon_found:
                            # 额外等待一段时间确保响应完全加载
                            self._update_progress(59, "Claude回复似乎已完成，额外等待确认...")
                            time.sleep(2)
                            
                            # 再次检查所有指示器和上传图标
                            still_all_gone = True
                            for indicator in typing_indicators:
                                try:
                                    indicator_elements = self.driver.find_elements(By.XPATH, indicator)
                                    if indicator_elements and indicator_elements[0].is_displayed():
                                        still_all_gone = False
                                        break
                                except:
                                    pass
                            
                            # 再次检查上传图标状态
                            upload_icon_still_found = False
                            if not still_all_gone:  # 如果仍有指示器存在，不需要再检查上传图标
                                continue
                                
                            # 如果指示器都消失了，检查上传图标是否仍存在
                            if not upload_icon_found:  # 如果之前没检测到上传图标，再次尝试
                                try:
                                    for icon_selector in upload_icon_selectors:
                                        icons = self.driver.find_elements(By.XPATH, icon_selector)
                                        if icons and any(icon.is_displayed() for icon in icons):
                                            upload_icon_still_found = True
                                            break
                                except:
                                    pass
                            else:
                                upload_icon_still_found = True  # 如果之前检测到了，假设仍存在
                            
                            if still_all_gone or upload_icon_still_found:
                                self._update_progress(59, f"Claude回复已完成 {'(检测到上传图标)' if upload_icon_still_found else '(所有指示器已消失)'}")
                                return  # 成功完成，退出函数
                        
                        time.sleep(1)  # 每秒检查一次状态
                        
                    # 如果执行到这里，说明已经成功处理，退出重试循环
                    break
                    
                except StaleElementReferenceException as e:
                    attempt += 1
                    if attempt < max_attempts:
                        self._update_progress(59, f"等待过程中元素引用过期，重试中 ({attempt}/{max_attempts}): {str(e)}")
                        time.sleep(2)
                    else:
                        raise TimeoutException(f"等待响应过程中遇到多次元素引用过期错误: {str(e)}")
                except Exception as e:
                    attempt += 1
                    if attempt < max_attempts:
                        self._update_progress(59, f"等待过程中发生错误，重试中 ({attempt}/{max_attempts}): {str(e)}")
                        time.sleep(2)
                    else:
                        raise
            
        except TimeoutException as e:
            # 记录超时时的页面状态
            try:
                screenshot_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 
                                               "timeout_screenshot.png")
                self.driver.save_screenshot(screenshot_path)
                self._update_progress(59, f"等待响应超时，已保存截图到 {screenshot_path}")
            except:
                pass
            raise TimeoutException(f"等待Claude响应超时: {str(e)}")
    
    def _get_latest_response(self) -> str:
        """
        获取最新的一条响应
        
        Returns:
            Claude的响应文本
        """
        # 增加重试机制
        max_attempts = 3
        for attempt in range(max_attempts):
            try:
                # 定义可能的响应元素选择器
                response_selectors = [
                    # 最新Claude响应格式 - 基于示例
                    "//div[contains(@class, 'grid-cols-1') and contains(@class, 'grid') and contains(@class, 'gap-2.5')]",
                    "//div[contains(@class, 'grid-cols-1')]",
                    "//div[contains(@class, 'grid') and contains(@class, 'gap-2.5')]",
                    
                    # 可能的响应内容容器
                    "//div[contains(@class, 'markdown')]",
                    "//div[contains(@class, 'message-content')]",
                    "//div[contains(@class, 'claude-message')]",
                    "//div[contains(@class, 'assistant-message')]",
                    "//div[contains(@class, 'markdown-content')]",
                    "//div[contains(@class, 'prose')]",
                    "//div[contains(@class, 'message')][last()]"
                ]
                
                # 等待响应元素加载
                response_element = None
                used_selector = ""
                for selector in response_selectors:
                    try:
                        elements = WebDriverWait(self.driver, 10).until(
                            EC.presence_of_all_elements_located((By.XPATH, selector))
                        )
                        
                        if elements:
                            # 获取最后一个元素（最新的响应）
                            response_element = elements[-1]
                            used_selector = selector
                            
                            # 确认元素是否可交互
                            self.driver.execute_script("return arguments[0].isConnected", response_element)
                            self._update_progress(60, f"找到响应元素，使用选择器: {selector}")
                            break
                    except StaleElementReferenceException:
                        # 如果元素引用过期，继续尝试下一个选择器
                        continue
                    except:
                        continue
                
                if response_element:
                    try:
                        # 检测是否是最新格式的Claude响应 - 含有段落元素的网格结构
                        if "grid-cols-1" in used_selector or "grid" in used_selector:
                            self._update_progress(60, "检测到最新格式的Claude响应，使用增强解析方法")
                            
                            # 为最新格式的响应使用特殊处理
                            js_enhanced_text_getter = """
                                function getFormattedText(element) {
                                    let text = '';
                                    
                                    // 专门处理带有p标签的网格布局响应
                                    const paragraphs = element.querySelectorAll('p');
                                    if (paragraphs && paragraphs.length > 0) {
                                        for (let i = 0; i < paragraphs.length; i++) {
                                            // 获取段落文本，保留格式化
                                            let paraText = paragraphs[i].innerText || paragraphs[i].textContent;
                                            
                                            // 保留粗体、斜体等格式
                                            const strongs = paragraphs[i].querySelectorAll('strong');
                                            for (let s = 0; s < strongs.length; s++) {
                                                paraText = paraText.replace(strongs[s].textContent, '**' + strongs[s].textContent + '**');
                                            }
                                            
                                            const italics = paragraphs[i].querySelectorAll('em');
                                            for (let it = 0; it < italics.length; it++) {
                                                paraText = paraText.replace(italics[it].textContent, '*' + italics[it].textContent + '*');
                                            }
                                            
                                            text += paraText + '\\n\\n';
                                        }
                                        return text;
                                    }
                                    
                                    // 备用：如果上面方法失败，则获取所有文本内容
                                    return element.innerText || element.textContent;
                                }
                                return getFormattedText(arguments[0]);
                            """
                            
                            enhanced_text = self.driver.execute_script(js_enhanced_text_getter, response_element)
                            if enhanced_text and enhanced_text.strip():
                                return enhanced_text.strip()
                                
                        # 使用JavaScript获取文本内容可以避免一些StaleElementReference问题
                        response_text = self.driver.execute_script("return arguments[0].textContent", response_element)
                        if response_text and response_text.strip():
                            return response_text
                        else:
                            # 尝试常规方法
                            return response_element.text
                    except StaleElementReferenceException:
                        # 如果获取文本时元素引用过期，重试
                        if attempt < max_attempts - 1:
                            self._update_progress(60, f"获取响应内容时元素引用过期，重试中 ({attempt+1}/{max_attempts})")
                            time.sleep(1)
                            continue
                        else:
                            raise
                    except Exception as e:
                        # 记录错误并尝试其他获取文本的方法
                        self._update_progress(60, f"获取响应文本错误: {str(e)}，尝试备用方法")
                        
                        # 尝试备用方法：使用JavaScript遍历所有文本节点
                        try:
                            js_text_getter = """
                                function getAllText(element) {
                                  let text = '';
                                  // 获取所有文本节点
                                  for (let i = 0; i < element.childNodes.length; i++) {
                                    const node = element.childNodes[i];
                                    if (node.nodeType === Node.TEXT_NODE) {
                                      text += node.textContent;
                                    } else if (node.nodeType === Node.ELEMENT_NODE) {
                                      text += getAllText(node);
                                      // 添加换行符以模拟段落分隔
                                      if (node.tagName === 'P' || node.tagName === 'DIV' || 
                                          node.tagName === 'BR' || node.tagName === 'LI') {
                                        text += '\n';
                                      }
                                    }
                                  }
                                  return text;
                                }
                                return getAllText(arguments[0]);
                            """
                            
                            backup_text = self.driver.execute_script(js_text_getter, response_element)
                            if backup_text and backup_text.strip():
                                return backup_text
                        except Exception as e2:
                            self._update_progress(60, f"备用文本获取方法也失败: {str(e2)}")

                # 如果没有找到响应元素，尝试截图
                if attempt < max_attempts - 1:
                    self._update_progress(60, f"未找到响应元素，重试中 ({attempt+1}/{max_attempts})")
                    time.sleep(2)
                else:
                    try:
                        screenshot_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 
                                                   "response_not_found.png")
                        self.driver.save_screenshot(screenshot_path)
                        self._update_progress(60, f"无法获取响应内容，已保存截图到 {screenshot_path}")
                    except:
                        pass
            except Exception as e:
                if attempt < max_attempts - 1:
                    self._update_progress(60, f"获取响应过程中发生错误，重试中 ({attempt+1}/{max_attempts}): {str(e)}")
                    time.sleep(2)
                else:
                    print(f"获取响应失败，已尝试 {max_attempts} 次: {str(e)}")
        
        # 如果所有尝试都失败
        return "无法获取响应内容，请检查网页状态或刷新页面" 